<!DOCTYPE html>
<head lang = "en">
<head></head>    
    <meta charset="UTF-8">
    <title>贪吃蛇</title>
    <style>
        #canvas{border: 3px solid red;}
        button{
             background: #2f435e;
             color:#f2f2f2;
             padding : 10px;
             font-size : 16px;
             border-radius: 40px;
             transition:all linear 0.30s;
             width:200px;
             height: 50px;
        }
    </style>
</head>

<body>
    <canvas id = 'canvas' width = '800' height='600'></canvas>
    <script>
        var canvas = document.getElementById("canvas");
        var ctx = canvas.getContext('2d');
        var gridWidth = 20;
        var score = 0;
        var foods = new Array(), snakes = new Array();
        var di ;

        //方向修改传参用
        function chdi(index){
            di = index;
        }

        // 定义食物类
        function Food(x,y,w){
            var t = this;
            t.x = x;
            t.y = y;
            t.w = w;
            t. foodinit  = function (){
                ctx. beginPath();
                ctx. arc(x+w/2,y+w/2,w/2,0,360,false);
                ctx. fillStyle = 'red'; //填充颜色
                ctx. fill();
                ctx. closePath();
            }

            //判断是否重合
            t.equal = function(node){
                if (this.x == node.x && this.y == node.y){
                    return true;
                }else{
                    return false;
                }

            }
        }

        // 定义块类 

        function Block(x,y,w){
            var t = this;
            t.x = x;
            t.y = y;
            t.w = w;
            t.drawBlock = function(){
                ctx.beginPath();
                ctx.arc(x+w/2,y+w/2,w/2,0,360,false);
                ctx.fillStyle = 'white';
                ctx.fill();
                ctx.closePath();
            }

            t.clear = function(){
                ctx.fillStyle='black';
                ctx.strokeStyle = 'black';
                ctx.fillRect(x,y,w,w);
                ctx.strokeRect(x,y,w,w);
            }
            
            //判断是否重合
            t.equal = function(node){
                if (this.x == node.x && this.y == node.y){
                    return true;
                }else{
                    return false;
                }

            }

        } 

        
        //蛇类
        function Snake(x,y,len,speed){
            var t = this;
            t.x = x;
            t.y = y;
            t.dir = 'R';
            t.len = len;
            var nx = x ;  ny = y;
            t.init = function(){
                for (var i = 0; i<len;i++){
                    var temBlock = new Block(nx,ny,gridWidth);
                    temBlock.drawBlock();
                    nx -= gridWidth;
                    snakes.push(temBlock); // 将该元素存进数组snakes
                };
                snake_interval = setInterval(t.move,speed);//定时移动蛇
            }

            document.onkeydown = function(e){
            var code = e.keyCode;
            t.odir = t.dir; //获取初始方向
            switch(code){
                case 37:
                    t.dir = 'L';
                    break;
                case 38:
                    t.dir = 'U';
                    break;
                case 39:
                    t.dir = 'R';
                    break;
                case 40:
                    t.dir = 'D'
                    break;
            }
            }

            //蛇的移动
            t.move = function(){
                //手机上的解决方案
                t.odir = t.dir;
                switch (di) {
                   case 1:
                       t.dir = 'L';
                       di = 0;
                       break;
                   case 2:
                       t.dir = 'U';
                       di = 0;
                       break;
                   case 3:
                       t.dir = 'R';
                       di = 0;
                       break;
                   case 4:
                       t.dir = 'D';
                       di = 0;
                       break;
               }

                var newHead;
                if(snakes[0].x+snakes[0].w >= canvas.width|| snakes[0].x-snakes[0].w<0||snakes[0].y+snakes[0].w >= canvas.height|| snakes[0].y-snakes[0].w<0){
                    gameover();
                }
                else{
                   if(t.dir == 'R'){
                   newHead = new Block(snakes[0].x+gridWidth,snakes[0].y,gridWidth);
                   }else if(t.dir == 'L'){
                    newHead = new Block(snakes[0].x-gridWidth,snakes[0].y,gridWidth);
                   }else if(t.dir == 'D'){
                    newHead = new Block(snakes[0].x,snakes[0].y+gridWidth,gridWidth);
                   }else if(t.dir == 'U'){
                    newHead = new Block(snakes[0].x,snakes[0].y-gridWidth,gridWidth);     
                   }
                }

                if (newHead.x == snakes[1].x && newHead.y == snakes[1].y){
                    t.dir = t.odir;
                    return
                }

                newHead.drawBlock();
                snakes.unshift(newHead);
                snakes[snakes.length-1].clear();
                snakes.pop();

                //吃到食物时
                for(var i = 0;i<foods.length;i++){
                    if(foods[i].equal(snakes[0])){
                        t.growth();
                        t.len = t.len+1;
                        clearInterval(snake_interval);
                        speed = speed< 20?speed:speed-10;
                        snake_interval = setInterval(t.move,speed);
                    }
                }

                //自我碰撞时
                for(var i =1; i<snakes.length;i++){
                    if(snakes[i].equal(snakes[0])){
                        gameover();
                    }
                };
            }

            t.growth = function(){
                var tail1 = snakes[snakes.length-1];
                var tail2 = snakes[snakes.length-2];
                var addBlock;
                if(tail1.x==tail2.x){
                    if(tail1.y >= tail2.y)
                        addBlock = new Block(tail1.x,tail1.y+gridWidth,gridWidth);
                    else
                        addBlock = new Block(tail1.x,tail1.y-gridWidth,gridWidth);
                    
                }
                else{
                    if(tail2.x>=tail2.x)
                        addBlock = new Block(tail1.x+gridWidth,tail1.y,gridWidth);
                    else
                        addBlock = new Block(tail1.x-gridWidth,tail1.y,gridWidth);
                }

                snakes.push(addBlock);
                addBlock.drawBlock();
                //console.log(snakes.length);
            }
    
        }

        //地图类
        function Farm(){
            var t =this;
            ctx.fillStyle = 'black';
            ctx.fillRect(0,0,canvas.width,canvas.height);
            foods = [];
            t.addfood = function(){
                var x = parseInt(canvas.width/gridWidth*Math.random())*gridWidth;
                console.log("ddd")
                var y = parseInt(canvas.height/gridWidth*Math.random())*gridWidth;
                var food  = new Food(x,y,gridWidth);
                food.foodinit();
                foods.push(food);
                
            }
            snakes = [];
            t.snake =  new Snake(100,100,5,500);
            t.snake.init();
        }
        
       

        function gamestart(){
            var map = new Farm();
            food_interval = setInterval(map.addfood,2000);
        }

        gamestart();
        
        function gameover(){
            var judge = confirm("结束了，要再来过吗？");
            score = 0;
            
            clearInterval(snake_interval);
            clearInterval(food_interval);
       
            gamestart();
        }
    </script>
<div>
    <button id = "up" onclick = "chdi(2);">up</button>
    <button id = "do" onclick = "chdi(4)">down</button>
    <button id = "ri" onclick = "chdi(3)">right</button>
    <button id = "le" onclick = "chdi(1)">left</button>
    <button onclick = dfs()>启动深搜</button>
</div>
</html>